//
//  WCNCareSchemeVC.m
//  WCN
//
//  Created by 杨鑫 on 15/7/1.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNCareSchemeVC.h"
//
#import "WCNSysDetailTCell.h"
#import "WCPickerView.h"
#import "WCButton.h"
//
#import "UINavigationItem+Offset.h"
#import "NSString+Utilities.h"
#import "NSObject+Utilities.h"
//
#import "PatientSchemeEntity.h"
//
#import "WCDefaultManager.h"
#import "WCCoreDataStore.h"
#import "WCNConstantsCDStore.h"
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
//
#import "Macros.h"
#import "Constants.h"

@interface WCNCareSchemeVC ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) Patient *patient;
@property (strong, nonatomic) PatientScheme *scheme;
@property (strong, nonatomic) PatientSchemeEntity *editScheme;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSArray *offerCareCases;

@end

@implementation WCNCareSchemeVC

- (instancetype)initWithPatient:(Patient *)patient withScheme:(PatientScheme *)scheme
{
    self = [super init];
    if (self) {
        self.title = @"护理方案设置";
        
        _patient = patient;
        if (scheme) {
            _scheme = scheme;
            _editScheme = [[PatientSchemeEntity alloc] initWithPatientScheme:scheme];
        } else {
            _editScheme = [[PatientSchemeEntity alloc] init];
            _editScheme.recordId = patient.stringId;
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem addRightBarButtonItem:rightBtn];
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerClass:[WCNSysDetailTCell class] forCellReuseIdentifier:@"WCNSysDetailTCell"];
}

- (void)save
{
    if (self.editScheme.templateCaseId == 0) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择护理方案" withView:self.view];
        return;
    }
    
    if (self.editScheme.startDay == 0) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择当前进度" withView:self.view];
        return;
    }
    
    if (!self.editScheme.status) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择状态" withView:self.view];
        return;
    }
    
    if (!self.editScheme.bodyPartCode) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择伤口部位" withView:self.view];
        return;
    }
    
    Account *account = [[WCDefaultManager shareMg] account];
    
    NSString *url;
    NSMutableDictionary *params = [[NSObject getObjectData:self.editScheme] mutableCopy];
    if (self.scheme) {
        url = @"nursing/case/update";
        
        params[@"id"] = params[@"stringId"];
        params[@"updateBy"] = account.stringId;
        
        [params removeObjectForKey:@"stringId"];
        [params removeObjectForKey:@"startDate"];
        
    } else {
        url = @"nursing/case/add";
        
        params[@"createBy"] = account.stringId;
        
        [params removeObjectForKey:@"stringId"];
        [params removeObjectForKey:@"startDate"];
    }
    
    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.navigationController.view];
    [[WCNetworkAccessManager sharedMg] POST:url parameters:params success:^(NSDictionary *result){
        [[WCPopupLayerManager shareMg] showTextOnly:result[@"errMsg"] withView:self.view];
        [self.navigationController popViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:CareSchemeListRefreshNotification object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:CareRecordsRefreshNotification object:nil];
    } failure:nil netError:nil always:^{
        [hud hide:YES];
    }];
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.scheme && indexPath.row != 2) {
        return;
    }
    
    switch (indexPath.row) {
        case 0:{
            void (^selectCase)(void) = ^{
                NSUInteger index = 0;
                for (CareCase *care in self.offerCareCases) {
                    if ([care.stringId intValue] == self.editScheme.templateCaseId) {
                        break;
                    }
                    index++;
                }
                
                WCPickerView *picker = [[WCPickerView alloc] init];
                picker.titleLabel.text = @"选择护理方案";
                picker.pickerDataSource = self.offerCareCases;
                [picker.picker selectRow:index inComponent:0 animated:YES];
                picker.close = ^(NSInteger selected){
                    CareCase *care = self.offerCareCases[selected];
                    self.editScheme.templateCaseId = [care.stringId intValue];
                    self.editScheme.templateCaseName = care.name;
                    
                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                };
                [picker show:self.navigationController completion:nil];
            };
            
            if (self.offerCareCases) {
                selectCase();
            } else {
                MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.view];
                [[WCNetworkAccessManager sharedMg] GET:@"template/nursing/case/list" parameters:nil success:^(NSDictionary *result){
                    self.offerCareCases = [[WCNConstantsCDStore shareStore] createCareCases:result[@"data"]];
                    selectCase();
                } failure:nil netError:nil always:^{
                    [hud hide:YES];
                }];
            }
            break;
        }
        case 1:{
            NSUInteger index = 0;
            NSMutableArray *days = [NSMutableArray array];
            for (int i=1; i<=100; i++) {
                if (self.editScheme.startDay == i) {
                    index = i-1;
                }
                [days addObject:[NSString stringWithFormat:@"%d", i]];
            }
            
            WCPickerView *picker = [[WCPickerView alloc] init];
            picker.titleLabel.text = @"天数";
            picker.pickerDataSource = days;
            [picker.picker selectRow:index inComponent:0 animated:YES];
            picker.close = ^(NSInteger selected){
                self.editScheme.startDay = (int)selected+1;
                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            };
            [picker show:self.navigationController completion:nil];
            break;
        }
        case 2:{
            NSUInteger index = 0;
            if ([@"IN_PROGRESS" isEqualToString:self.editScheme.status]) {
                index = 0;
            } else if ([@"COMPLETED" isEqualToString:self.editScheme.status]) {
                index = 1;
            }
            
            WCPickerView *picker = [[WCPickerView alloc] init];
            picker.titleLabel.text = @"状态";
            picker.pickerDataSource = @[@"进行中", @"已完结"];
            [picker.picker selectRow:index inComponent:0 animated:YES];
            picker.close = ^(NSInteger selected){
                if (selected == 0) {
                    self.editScheme.status = @"IN_PROGRESS";
                } else if (selected == 1) {
                    self.editScheme.status = @"COMPLETED";
                }
                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            };
            [picker show:self.navigationController completion:nil];
            break;
        }
        case 3:{
            NSUInteger index = 0;
            for (NSDictionary *part in self.offerCareParts) {
                NSString *partCode = part[@"bodyPartCode"];
                if ([partCode isEqualToString:self.editScheme.bodyPartCode]) {
                    break;
                }
                index++;
            }
            
            WCPickerView *picker = [[WCPickerView alloc] init];
            picker.titleLabel.text = @"伤口部位";
            picker.pickerDataSource = self.offerCareParts;
            picker.showKey = @"bodyPartName";
            [picker.picker selectRow:index inComponent:0 animated:YES];
            picker.close = ^(NSInteger selected){
                NSDictionary *part = self.offerCareParts[selected];
                self.editScheme.bodyPartCode = part[@"bodyPartCode"];
                self.editScheme.bodyPartName = part[@"bodyPartName"];
                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            };
            [picker show:self.navigationController completion:nil];
            break;
        }
            
        default:
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WCNSysDetailTCell" forIndexPath:indexPath];
    [cell setSeparatorInset:UIEdgeInsetsZero];
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    switch (indexPath.row) {
        case 0:{
            cell.textLabel.text = @"护理方案:";
            cell.detailTextLabel.text = self.editScheme.templateCaseName;
            break;
        }
        case 1:{
            cell.textLabel.text = @"当前进度:";
            if (self.editScheme.startDay > 0) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", self.editScheme.startDay];
            }
            break;
        }
        case 2:{
            cell.textLabel.text = @"状态:";
            if ([@"IN_PROGRESS" isEqualToString:self.editScheme.status]) {
                cell.detailTextLabel.text = @"进行中";
            } else if ([@"COMPLETED" isEqualToString:self.editScheme.status]) {
                cell.detailTextLabel.text = @"已完结";
            }
            break;
        }
        case 3:{
            cell.textLabel.text = @"伤口部位:";
            cell.detailTextLabel.text = self.editScheme.bodyPartName;
            break;
        }
        default:
            break;
    }
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

@end
